require(["core", "jQuery", "coAjax", "queryString", "href", "hash_routie"], function(jSouper, $, coAjax, QueryString, href, hash_routie) {
	var space_use_state_list = [];
	jSouper.forEach(appConfig.SPACE_USE_STATE, function(v, k) {
		space_use_state_list.push({
			value: v,
			title: k
		});
	});
	App.set("$Cache.bus.space_use_state_list", space_use_state_list);

	function _refresh_seat() {
		coAjax.get(appConfig.bus.space_list_by_type, {
			type: appConfig.SPACE_TYPE["桌号"]
		}, function(result) {
			App.set("$Cache.bus.space_seat.list", result.result);
		});
	};
	hash_routie.on("space-seat", _refresh_seat);

	App.set("$Event.bus.space.add_seat", function() {
		var space_info = App.get("$Cache.bus.space.new_seat");
		if (!space_info) {
			return;
		}
		space_info.type = appConfig.SPACE_TYPE["桌号"];
		coAjax.post(appConfig.bus.add_space, space_info, function(result) {
			alert("success", "新增桌号成功");
			App.push("$Cache.bus.space_seat.list", result.result);
			//自动增加桌号
			var _lastest_match_value;
			var _lastest_match_index;
			space_info.name.replace(/\d+/g, function(v, index) {
				_lastest_match_value = v;
				_lastest_match_index = index;
				return v;
			});
			if (_lastest_match_index) {
				var seat_name = space_info.name.substr(0, _lastest_match_index) + (~~_lastest_match_value + 1) + space_info.name.substr(_lastest_match_index + _lastest_match_value.length);
				App.set("$Cache.bus.space.new_seat.name", seat_name);
			}

		});
	});
	App.set("$Event.bus.space.change_seat", function(e, vm) {
		coAjax.put(appConfig.bus.update_space + vm.get("_id"), vm.get(), function(result) {
			alert("success", "修改成功")
			vm.set(result.result);
		});
	});
	App.set("$Event.bus.space.remove_seat", function(e, vm) {
		myConfirm("确定删除这个桌位？", function() {
			coAjax["delete"](appConfig.bus.remove_space + vm.get("_id"), function(result) {
				alert("删除成功")
				_refresh_seat();
			});
		});
	});
	/*
	 * Sock的事件通知
	 */
	var bus_notify = App.get("$Cache.bus_notify");
	bus_notify.on("bus.space.use_state.changed", function(space) {
		var space_seat_list = App.get("$Cache.bus.space_seat.list");
		space_seat_list = space_seat_list.map(function(space_info) {
			if (space_info._id == space._id) {
				return space
			} else {
				return space_info
			}
		});
		App.set("$Cache.bus.space_seat.list", space_seat_list);
	})
});